# api-service/main.py
from fastapi import FastAPI, BackgroundTasks
from pydantic import BaseModel
import httpx
import json
import asyncio
from typing import List, Optional

app = FastAPI(title="SHEIN Product Governance API")


class StandardizeRequest(BaseModel):
    product_id: str
    original_title: str
    original_description: str
    target_languages: List[str] = ["en", "es", "ar"]


class DetectionRequest(BaseModel):
    product_id: str
    content: dict
    check_types: List[str] = ["trademark", "prohibited_words"]


@app.post("/api/v1/product/standardize")
async def standardize_product(request: StandardizeRequest):
    """商品标准化接口"""
    # 1. 调用RAG获取相关知识
    async with httpx.AsyncClient() as client:
        rag_response = await client.post(
            "http://rag-service:8001/v1/retrieve",
            json={"text": request.original_title, "top_k": 3}
        )
        knowledge = rag_response.json()["results"]

    # 2. 构建增强提示词
    enhanced_prompt = f"""
    基于以下商品信息和相关知识，生成{', '.join(request.target_languages)}版本的标准标题和描述：

    原始标题：{request.original_title}
    原始描述：{request.original_description}

    相关知识：
    {chr(10).join([k['content'] for k in knowledge])}

    要求：
    - 符合电商平台规范
    - 包含关键词优化
    - 不同语言保持语义一致
    """

    # 3. 调用模型生成
    async with httpx.AsyncClient() as client:
        model_response = await client.post(
            "http://model-service:8000/v1/generate",
            json={"prompt": enhanced_prompt, "max_tokens": 1024}
        )
        generated_text = model_response.json()["text"]

    return parse_generated_content(generated_text)


@app.post("/api/v1/product/detect")
async def detect_violation(request: DetectionRequest):
    """违规检测接口"""
    detection_prompt = f"""
    检测以下商品内容是否违规：

    商品内容：{json.dumps(request.content, ensure_ascii=False)}
    检测类型：{', '.join(request.check_types)}

    请分析是否存在：
    1. 品牌侵权
    2. 违禁词汇  
    3. 敏感内容

    返回JSON格式：
    {{
        "violations": [
            {{
                "type": "违规类型",
                "content": "违规内容", 
                "confidence": 0.95,
                "suggestion": "改进建议"
            }}
        ],
        "risk_level": "high|medium|low"
    }}
    """

    async with httpx.AsyncClient() as client:
        response = await client.post(
            "http://model-service:8000/v1/generate",
            json={"prompt": detection_prompt, "max_tokens": 512}
        )
        result = json.loads(response.json()["text"])

    return result